package com.ruoyi.framework.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ijpay.core.IJPayHttpResponse;
import com.ijpay.core.enums.RequestMethod;
import com.ijpay.core.kit.PayKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.enums.WxDomain;
import com.ijpay.wxpay.model.v3.RefundAmount;
import com.ijpay.wxpay.model.v3.RefundModel;
import com.ruoyi.framework.config.PayConfig;
import com.ruoyi.framework.config.properties.WxpayPropertis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

/**
 * @author dyun
 */
@Configuration
@Slf4j
public class PayUtils {

    /**
     * 微信退款
     *
     * @param orderSn 订单号
     * @param refund  退款金额
     * @param total   实际支付金额
     * @return 是否退款成功
     */
    public static boolean wxpayRefund(String orderSn, int refund, int total) {
        WxpayPropertis wxpayPropertis = SpringUtil.getBean(WxpayPropertis.class);
        String outRefundNo = PayKit.generateStr();
        log.info("商户退款单号: {}", outRefundNo);

        RefundModel refundModel = new RefundModel()
                .setOut_trade_no(orderSn)
                .setOut_refund_no(outRefundNo)
                .setReason("平台退款")
                .setAmount(new RefundAmount().setRefund(refund).setTotal(total).setCurrency("CNY"));

        IJPayHttpResponse response;
        try {
            response = WxPayApi.v3(
                    RequestMethod.POST,
                    WxDomain.CHINA.toString(),
                    WxApiType.DOMESTIC_REFUNDS.toString(),
                    wxpayPropertis.getMchId(),
                    PayConfig.getSerialNumber(wxpayPropertis),
                    null,
                    wxpayPropertis.getPemKeyPath(),
                    JSONUtil.toJsonStr(refundModel)
            );

            // 根据证书序列号查询对应的证书来验证签名结果 todo wechat bug
            boolean verifySignature = WxPayKit.verifySignature(response, wxpayPropertis.getPemCertPath());
            log.info("verifySignature: {}", verifySignature);
            log.info("退款响应 {}", response);

//            if (verifySignature) {
            String body = response.getBody();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String status = jsonObject.getStr("status");
            if ("PROCESSING".equals(status)) {
                return true;
            }
//            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            return false;
        }
        return false;
    }

    public static void alipayRefund() {

    }
}
